package com.ybkj.chat.net.converter;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.ybkj.chat.utils.AESUtil;
import com.ybkj.chat.utils.DateUtil;
import com.ybkj.chat.utils.LogUtil;
import com.ybkj.chat.utils.RSAUtil;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Converter;

public class IRequestBodyConverter<T> implements Converter<T, RequestBody> {
    private static final MediaType MEDIA_TYPE = MediaType
            .parse("application/json; charset=UTF-8");
    static final Charset UTF_8 = Charset.forName("UTF-8");

    final Gson gson;
    final TypeAdapter<T> adapter;

    IRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
        System.out.println("#IRequestBodyConverter初始化#");
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        String AESKey = AESUtil.generateAESSecretKey();
        RequestData requestData = new RequestData();
        String data = value.toString();
        String dataStr = "";
        data = data + "&timestamp=" + DateUtil.getCurrentTimeMillis();
        data = data + "&dataCount=" + data.length();
        dataStr = data;
        LogUtil.e("YYJ","#加密前#" + data);
        data = AESUtil.AesEcbEncode(data, AESKey);
        requestData.data = data;
        requestData.sign = RSAUtil.sign(dataStr,RSAUtil.PRIVARE_KEY);
        requestData.key = RSAUtil.encrypt(RSAUtil.PUBLIC_KEY,AESKey);
        String json = new Gson().toJson(requestData);
        System.out.println("#加密后#" + json);
        return RequestBody.create(MEDIA_TYPE, json);
    }

    class RequestData{
        public String data;
        public String sign;
        public String key;
    }
}
